#    Copyright (C) 2019 Mason Hock <mason@masonhock.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
#

import random
import requests

from .library import Library


class Channel:
    def __init__(self, musicbrainz_artist_data):
        self.pool = Library()

        url = "https://api.jamendo.com/v3.0/tracks/?"

        options = [
            ("client_id", "8e4fe531"),
            ("format", "jsonpretty"),
            ("ccnc", "0"),
            ("ccnd", "0"),
        ]

        xartist_options = options + [
            ("limit", "all"),
            ("xartist", musicbrainz_artist_data["name"]),
        ]

        tags = [
            tag["name"]
            for tag in musicbrainz_artist_data["tag-list"]
            if int(tag["count"]) > 0
        ]

        tags_options = options + [("limit", "all"), ("fuzzytags", "+".join(tags))]

        for result in requests.get(
            url + "&".join(["=".join(option) for option in xartist_options])
        ).json()["results"]:
            self.pool.add_jamendo_track(result)

        for result in requests.get(
            url + "&".join(["=".join(option) for option in tags_options])
        ).json()["results"]:
            self.pool.add_jamendo_track(result)

    def get_random_track(self):
        track_id = random.choice(list(self.pool))
        return self.pool.get_track(track_id)
